package com.pdstudio.carrecom.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.pdstudio.carrecom.api.HttpExecuteJson;
import com.pdstudio.carrecom.api.ServiceHelper;
import com.pdstudio.carrecom.api.HttpExecuteJson.httpReturnJson;
import com.pdstudio.carrecom.app.AppContext;
import com.pdstudio.carrecom.app.UIHelper;
import com.pdstudio.carrecom.bean.GuidePage;
import com.pdstudio.carrecom.bean.InitPage;
import com.pdstudio.carrecom.bean.GuidePage.ImageP;
import com.pdstudio.carrecom.bean.ResultInfo;
import com.pdstudio.carrecom.tools.JsonUtil;
import com.pdstudio.carrecom.ui.adapter.ViewPagerAdapter;
import com.pdstudio.carrecom.R;

/**
 * 
 * @{# GuideActivity.java Create on 2013-5-2 下午10:59:08
 * 
 *     class desc: 引导界面
 * 
 *     <p>
 *     Copyright: Copyright(c) 2013
 *     </p>
 * @Version 1.0
 * @Author <a href="mailto:gaolei_xj@163.com">Leo</a>
 * 
 * 
 */
public class GuideActivity extends Activity implements OnPageChangeListener {

	private ViewPager vp;
	private ViewPagerAdapter vpAdapter;
	private List<View> views;

	// 底部小点图片
	private ImageView[] dots;

	// 记录当前选中位置
	private int currentIndex;
	
	//当前的图片控件
	private ImageView loadingI;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		SharedPreferences preferences = getSharedPreferences("nexttime",
				MODE_PRIVATE);
		boolean show = preferences.getBoolean("shownexttime", true);
		show=true;
		if (show) {

			setContentView(R.layout.guide);

			// 初始化页面
			//initViews();
			
			initData();

			// 初始化底部小点
			//initDots();
			
		}else{
			if (!AppContext.getInstance().autoLogin()) {
				Intent intent = new Intent(GuideActivity.this,
						ActivityLogin.class);
				startActivity(intent);
				finish();
			} else {
				AppContext.getInstance()._isLogin = true;

				Intent intent = new Intent(GuideActivity.this,
						ActivityMain.class);
				startActivity(intent);
				finish();
			}
		}
	}

	private void initViews() {
	}

	private void initDots() {
		LinearLayout ll = (LinearLayout) findViewById(R.id.ll);

		dots = new ImageView[views.size()];

		// 循环取得小点图片
		for (int i = 0; i < views.size(); i++) {
			dots[i] = (ImageView) ll.getChildAt(i);
			dots[i].setEnabled(true);// 都设为灰色
		}

		currentIndex = 0;
		dots[currentIndex].setEnabled(false);// 设置为白色，即选中状态
	}

	private void setCurrentDot(int position) {
		if (position < 0 || position > views.size() - 1
				|| currentIndex == position) {
			return;
		}

		dots[position].setEnabled(false);
		dots[currentIndex].setEnabled(true);

		currentIndex = position;
	}

	// 当滑动状态改变时调用
	@Override
	public void onPageScrollStateChanged(int arg0) {
	}

	// 当当前页面被滑动时调用
	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	// 当新的页面被选中时调用
	@Override
	public void onPageSelected(int arg0) {
		// 设置底部小点选中状态
		setCurrentDot(arg0);
	}

	/*
	 * 处理json过来的数据*/
	private void DoJson(String json){
		ResultInfo edv = null;
		try {
			edv = new Gson().fromJson(json,
					new TypeToken<ResultInfo>() {
					}.getType());
			if ((edv != null)
					&& (edv.msg.equals(ServiceHelper.msg_code_sucess))) {
				List<ImageP> temps1 = new ArrayList<ImageP>();
				if(edv.data!=null){
					
					List<ImageP> ips=JsonUtil.fromJsonArray(JsonUtil.toJson(edv.data), ImageP.class);
					temps1=ips;
				}
				//原本在initview的代码放在这下面
				try{
					LayoutInflater inflater = LayoutInflater.from(GuideActivity.this);

					views = new ArrayList<View>();
					// 初始化引导图片列表
					//views.add(inflater.inflate(R.layout.what_new_one, null));
					//views.add(inflater.inflate(R.layout.what_new_two, null));
					//views.add(inflater.inflate(R.layout.what_new_three, null));
					//views.add(inflater.inflate(R.layout.what_new_four, null));
					int count=temps1.size();
					for(int i=0;i<count;i++){
						try{
							View v;
							if(i==(count-1)){
								//最后一张图
								v=inflater.inflate(R.layout.what_new_four, null);
								loadingI=(ImageView)v.findViewById(R.id.guide_loading4);	
							}else{
								v=inflater.inflate(R.layout.what_new_one, null);
								loadingI=(ImageView)v.findViewById(R.id.guide_loading1);
							}
							
							if(loadingI!=null){
								DisplayImageOptions options = new DisplayImageOptions.Builder()
								.displayer(new FadeInBitmapDisplayer(1000)) // 渐变动画
								.handler(new Handler()) // default
								.build();
								ImageLoader.getInstance().displayImage(temps1.get(i).url, loadingI, options);	
							}
							if(v!=null){
								views.add(v);
							}
							initDots();
						}catch(Exception e){e.printStackTrace();}
					}
					// 初始化Adapter
					vpAdapter = new ViewPagerAdapter(views, GuideActivity.this);

					vp = (ViewPager) findViewById(R.id.viewpager);
					vp.setAdapter(vpAdapter);
					// 绑定回调
					vp.setOnPageChangeListener(GuideActivity.this);

				}catch(Exception e){
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	//初始化数据，获取网络数据
	public void initData(){
		try {
			HttpExecuteJson http = new HttpExecuteJson(this, mGuidePicsListener);
			Map<String, Object> rps = new HashMap<String, Object>();
			rps.put("os", "android");
			rps.put("size", "20-40");
			rps.put("type", "0");
			http.get(ServiceHelper.GuidePage, rps);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	//
	private httpReturnJson mGuidePicsListener = new httpReturnJson() {
		@Override
		public void onFailure(int error, String msg) {
			UIHelper.ToastMessage(GuideActivity.this, "获取引导页失败" + msg);
		}

		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			UIHelper.ToastMessage(GuideActivity.this, "获取引导页退出");
		}

		// 获取到饲料配方类型成功
		public void onSuccess(String result) {
			// TODO Auto-generated method stub
			// UIHelper.ToastMessage(_context,"总条数=" + result + "");
			DoJson(result);
		}
	};
}
